package cryptoutil

import (
	"crypto/x509"
	"io/ioutil"
)

type CryptoSuite interface {
	NewSigner() (Signer, error)
	GetCreator() ([]byte, error)
}

type myCryptoSuite struct {
	privKey Key
	signCert *x509.Certificate
	mspID  string
}

func (cs myCryptoSuite) NewSigner() (Signer, error) {
	return &myCryptoSigner{
		priKey: cs.privKey,
		signCert: cs.signCert,
		mspID: cs.mspID,
	}, nil
}

func (cs myCryptoSuite) GetCreator() ([]byte, error) {
	signer, err := cs.NewSigner()
	if err != nil {
		return nil, err
	}
	return signer.Serialize()
}

func GetMyCryptoSuiteFromBytes(keyBytes, certBytes []byte, mspid string) (CryptoSuite, error) {
	signCert, err := getCertFromPem(certBytes)
	if err != nil {
		return nil, err
	}
	priKey, err := GetPrivateKeyFromPEM(keyBytes, nil)
	if err != nil {
		return nil, err
	}
	return &myCryptoSuite{
		privKey: priKey,
		signCert: signCert,
		mspID: mspid,
	}, nil
}

// GetMyCryptoSuiteFromFiles create cryptosuite from specified files
func GetMyCryptoSuiteFromFiles(keyFile, signCertFile string, mspid string) (CryptoSuite, error) {
	keyBytes, err := ioutil.ReadFile(keyFile)
	if err != nil {
		return nil, err
	}
	certBytes, err := ioutil.ReadFile(signCertFile)
	if err != nil {
		return nil, err
	}

	return GetMyCryptoSuiteFromBytes(keyBytes, certBytes, mspid)
}



